/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim </a>, 2004
 */
package hk.com.carfield.action.process;

import hk.com.carfield.core.Context;
import hk.com.carfield.util.FileObject;
import hk.com.carfield.util.FileUtil;
import hk.com.carfield.util.LogUtil;
import hk.com.carfield.web.Request;

import java.io.File;
import java.util.Collection;

public final class Upload implements Process {
	public String actionCode() {
		return "upload";
	}

	public boolean adminOnly() {
		return true;
	}

	public File process(final Context c, final Request req, final File l) {
		// TODO add validation
		// TODO see if add back checkbox for user to upload a zip file without
		// unzip
		final boolean isunzip = true;
		final Collection<FileObject> fileObjects = req.getFileObject();
		if (fileObjects.size() == 0) {
			LogUtil.log("FileObject is NULL!");
		}
		for (final FileObject fi : fileObjects) {
			final File newFile = new File(l.isDirectory() ? l
					: l.getParentFile(), fi.getName());
			final String extension = FileUtil.getExtensions(newFile);
			try {
				if (isunzip && "zip".equalsIgnoreCase(extension)) {
					final File temp = new File(c.config.getCacheDir(),
							fi.getName());
					fi.write(temp);
					FileUtil.unzip(temp, newFile);
					temp.delete();
				} else {
					fi.write(newFile);
				}
				fi.delete();
			} catch (final Exception e) {
				throw new RuntimeException(e);
			}
		}
		return l;
	}
}